package top.frsf.autocodegen.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.frsf.autocodegen.controller.dto.AutoDataSourceAddDTO;
import top.frsf.autocodegen.entity.AutoDatasource;
import top.frsf.autocodegen.entity.AutoTable;
import top.frsf.autocodegen.mapper.AutoDatasourceMapper;
import top.frsf.autocodegen.service.IAutoDatasourceService;
import top.frsf.autocodegen.utils.JdbcSessionFactoryUtil;
import top.frsf.autocodegen.utils.Result;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Desc
 *
 * @author FRSF
 * @since 2024/7/25 17:08
 */
@Service
public class AutoDatasourceServiceImpl extends ServiceImpl<AutoDatasourceMapper, AutoDatasource> implements IAutoDatasourceService {

    @Override
    public Result<Boolean> saveDatasource(AutoDataSourceAddDTO dto) {
        AutoDatasource build = AutoDatasource.builder()
                .name(dto.getName())
                .url(dto.getUrl())
                .username(dto.getUsername())
                .password(dto.getPassword())
                .build();
        int insert = baseMapper.insert(build);
        return insert > 0 ? Result.success(true) : Result.fail("添加失败");
    }

    @Override
    public AutoDatasource getDatasourceById(Integer id) {
        AutoDatasource datasource = this.getById(id);
        if (datasource == null) {
            throw new RuntimeException("数据源不存在");
        }
        return datasource;
    }

    @Override
    public List<AutoTable> listTableByDatasourceId(Integer id) throws SQLException, ClassNotFoundException {
        AutoDatasource datasource = this.getDatasourceById(id);
        try (Connection connection = JdbcSessionFactoryUtil.getSqlSessionFactory(datasource)) {
            PreparedStatement statement = connection.prepareStatement("select table_name, table_comment from information_schema.tables where table_schema = (select database())");
            ResultSet resultSet = statement.executeQuery();
            ArrayList<AutoTable> tables = new ArrayList<>();
            while (resultSet.next()) {
                AutoTable autoTable = AutoTable.builder()
                        .tableName(resultSet.getString("table_name"))
                        .tableComment(resultSet.getString("table_comment"))
                        .build();
                tables.add(autoTable);
            }
            return tables;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}



